package com.example.h1nson.realphotography.activity;


        import java.util.ArrayList;
        import java.util.List;
        import java.util.concurrent.Executors;
        import java.util.concurrent.ScheduledExecutorService;
        import java.util.concurrent.TimeUnit;

        import android.content.Intent;
        import android.graphics.Bitmap;
        import android.graphics.Matrix;
        import android.graphics.drawable.BitmapDrawable;
        import android.graphics.drawable.Drawable;
        import android.os.Handler;
        import android.os.Message;
        import android.support.v7.app.AppCompatActivity;
        import android.os.Bundle;
        import android.support.v4.app.Fragment;
        import android.support.v4.app.FragmentPagerAdapter;
        import android.support.v4.view.ViewPager;
        import android.support.v4.view.ViewPager.OnPageChangeListener;
        import android.view.KeyEvent;
        import android.view.View;
        import android.widget.ImageButton;
        import android.widget.LinearLayout;
        import android.widget.Toast;

        import com.example.h1nson.realphotography.R;
        import com.example.h1nson.realphotography.activity.imageloader.ImageGridActivity;
        import com.example.h1nson.realphotography.activity.imageloader.ImageListActivity;
        import com.example.h1nson.realphotography.config.ConfigURL;
        import com.example.h1nson.realphotography.config.GetCurrentUser;
        import com.example.h1nson.realphotography.entity.User;
        import com.example.h1nson.realphotography.interface_photo.OnFindBtnClickListener;
        import com.example.h1nson.realphotography.interface_photo.OnFindItemListener;
        import com.example.h1nson.realphotography.interface_photo.OnHomeInfoClickListener;
        import com.example.h1nson.realphotography.interface_photo.OnPushItemListener;
        import com.example.h1nson.realphotography.interface_photo.OnSearchItemListener;
        import com.example.h1nson.realphotography.viewpager.MainTab01;
        import com.example.h1nson.realphotography.viewpager.MainTab02;
        import com.example.h1nson.realphotography.viewpager.MainTab03;
        import com.example.h1nson.realphotography.viewpager.MainTab04;
        import com.pizidea.imagepicker.AndroidImagePicker;
        import com.shelwee.uilistview.model.BasicItem;
        import com.shelwee.uilistview.ui.UiListView;

        import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
        import org.eclipse.paho.client.mqttv3.MqttCallback;
        import org.eclipse.paho.client.mqttv3.MqttClient;
        import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
        import org.eclipse.paho.client.mqttv3.MqttException;
        import org.eclipse.paho.client.mqttv3.MqttMessage;
        import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class MainActivity extends AppCompatActivity
{
    public static MainActivity instance = null;
    private ViewPager mViewPager;
    private FragmentPagerAdapter mAdapter;
    private List<Fragment> mFragments = new ArrayList<Fragment>();

    /**
     * 底部四个按钮
     */
    private LinearLayout mTabBtnWeixin;
    private LinearLayout mTabBtnFrd;
    private LinearLayout mTabBtnAddress;
    private LinearLayout mTabBtnSettings;
    private String email;
    private User user;
    private ImageButton btn_camera;
    private MainTab02 tab02;
    private MainTab03 tab03;
    public  MainTab04 tab04;
    private MainTab01 tab01;
    private String host = "tcp://172.29.115.232:61613";
    private String userName = "admin";
    private String passWord = "password";
    private Handler handler;
    private MqttClient client;
    private String myTopic = "test/topic";
    private MqttConnectOptions options;
    private ScheduledExecutorService scheduler;
    private boolean mqtt;
    private long exitTime = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setCamera();
        mViewPager = (ViewPager) findViewById(R.id.id_viewpager);
        Intent intent = getIntent();
        //获取数据
        email = intent.getStringExtra("Email");
        initView();
        mAdapter = new FragmentPagerAdapter(getSupportFragmentManager())
        {

            @Override
            public int getCount()
            {
                return mFragments.size();
            }

            @Override
            public Fragment getItem(int arg0)
            {
                System.out.println("tiaozhaun");
                return mFragments.get(arg0);
            }
        };
        mViewPager.setOffscreenPageLimit(4);
        mViewPager.setAdapter(mAdapter);
        mViewPager.setOnPageChangeListener(new OnPageChangeListener()
        {

            private int currentIndex;

            @Override
            public void onPageSelected(int position)
            {
                //resetTabBtn();
//                switch (position)
//                {
//                    case 0:
//                        ((ImageButton) mTabBtnWeixin.findViewById(R.id.btn_tab_bottom_weixin))
//                                .setImageResource(R.drawable.tab_weixin_pressed);
//                        break;
//                    case 1:
//                        ((ImageButton) mTabBtnFrd.findViewById(R.id.btn_tab_bottom_friend))
//                                .setImageResource(R.drawable.tab_find_frd_pressed);
//                        break;
//                    case 2:
//                        ((ImageButton) mTabBtnAddress.findViewById(R.id.btn_tab_bottom_contact))
//                                .setImageResource(R.drawable.tab_address_pressed);
//                        break;
//                    case 3:
//                        ((ImageButton) mTabBtnSettings.findViewById(R.id.btn_tab_bottom_setting))
//                                .setImageResource(R.drawable.tab_settings_pressed);
//                        break;
//                }

                currentIndex = position;
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2)
            {

            }

            @Override
            public void onPageScrollStateChanged(int arg0)
            {
            }
        });
        mViewPager.setCurrentItem(0);
        instance = this;
        mqtt = intent.getBooleanExtra("Mqtt",false);
        if(mqtt){
            init();
        }

    }

    private void init() {
        try {
            //host为主机名，test为clientid即连接MQTT的客户端ID，一般以客户端唯一标识符表示，MemoryPersistence设置clientid的保存形式，默认为以内存保存
            client = new MqttClient(host, "test",
                    new MemoryPersistence());
            //MQTT的连接设置
            options = new MqttConnectOptions();
            //设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(true);
            //设置连接的用户名
            options.setUserName(userName);
            //设置连接的密码
            options.setPassword(passWord.toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
            options.setKeepAliveInterval(20);
            //设置回调
            client.setCallback(new MqttCallback() {

                @Override
                public void connectionLost(Throwable cause) {
                    //连接丢失后，一般在这里面进行重连
                    System.out.println("connectionLost----------");
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    //publish后会执行到这里
                    System.out.println("deliveryComplete---------"
                            + token.isComplete());
                }

                @Override
                public void messageArrived(String topicName, MqttMessage message)
                        throws Exception {
                    //subscribe后得到的消息会执行到这里面
                    System.out.println("messageArrived----------");
                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = topicName+"---"+message.toString();
                    handler.sendMessage(msg);
                }
            });
//          connect();
        } catch (Exception e) {
            e.printStackTrace();
        }

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if(msg.what == 1) {
                    Toast.makeText(MainActivity.this, (String) msg.obj,
                            Toast.LENGTH_SHORT).show();
                    System.out.println("-----------------------------");
                } else if(msg.what == 2) {
                    Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
                    try {
                        client.subscribe(myTopic, 1);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else if(msg.what == 3) {
                    Toast.makeText(MainActivity.this, "连接失败，系统正在重连", Toast.LENGTH_SHORT).show();
                }
            }
        };
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new Runnable() {

            @Override
            public void run() {
                if(!client.isConnected()) {
                    new Thread(new Runnable() {

                        @Override
                        public void run() {
                            try {
                                client.connect(options);
                                Message msg = new Message();
                                msg.what = 2;
                                handler.sendMessage(msg);
                            } catch (Exception e) {
                                e.printStackTrace();
                                Message msg = new Message();
                                msg.what = 3;
                                handler.sendMessage(msg);
                            }
                        }
                    }).start();
                }
            }
        }, 0 * 1000, 10 * 1000, TimeUnit.MILLISECONDS);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mqtt) {
            try {
                scheduler.shutdown();
                client.disconnect();
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
    }


    private void initView()
    {

        mTabBtnWeixin = (LinearLayout) findViewById(R.id.id_tab_bottom_weixin);
        mTabBtnWeixin.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {
                mViewPager.setCurrentItem(0);
            }
            });
        mTabBtnFrd = (LinearLayout) findViewById(R.id.id_tab_bottom_friend);
        mTabBtnFrd.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {
                mViewPager.setCurrentItem(1);
            }
        });
        mTabBtnAddress = (LinearLayout) findViewById(R.id.id_tab_bottom_contact);
        mTabBtnAddress.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {
                mViewPager.setCurrentItem(2);
            }
        });
        mTabBtnSettings = (LinearLayout) findViewById(R.id.id_tab_bottom_setting);
        mTabBtnSettings.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {
                mViewPager.setCurrentItem(3);
            }
        });

        tab01 = new MainTab01();
        tab01.setOnPushItemListener(new OnPushItemListener() {
            @Override
            public void goPhotoDetail(int photoId) {
                Intent intent = new Intent(MainActivity.this, PhotoDetailActivity.class);
                intent.putExtra("photoId",photoId);
                startActivity(intent);
            }
        });
        tab02 = new MainTab02();
        tab02.setOnSearchItemListener(new OnSearchItemListener() {
            @Override
            public void goDetail(int type,int Id) {
                if(type==0){
                    Intent intent = new Intent(MainActivity.this, UserInfoActivity.class);
                    intent.putExtra("userId",Id);
                    startActivity(intent);
                }else{
                    Intent intent = new Intent(MainActivity.this, PhotoDetailActivity.class);
                    intent.putExtra("photoId",Id);
                    startActivity(intent);
                }
            }
        });
        tab03= new MainTab03();
        tab03.setOnFindItemListener(new OnFindItemListener() {
            @Override
            public void goDedtail(int photoId) {
                Intent intent = new Intent(MainActivity.this, PhotoDetailActivity.class);
                intent.putExtra("photoId",photoId);
                startActivity(intent);
            }
        });
        tab04 = new MainTab04();
        tab04.setOnHomeInfoClickListener(new OnHomeInfoClickListener() {
            @Override
            public void changeUI(int index) {
                Intent intent;
                switch (index){
                    case 0://展示个人信息
                        AndroidImagePicker.getInstance().clear();
                        intent = new Intent(MainActivity.this,ModifyActivity.class);
                        startActivityForResult(intent,1000);
                        break;
                    case 1://关注列表
//                        intent = new Intent(MainActivity.this,IdolListActivity.class);
//                        startActivity(intent);
                        intent = new Intent(MainActivity.this, ImageListActivity.class);
                        //intent.putExtra(Constants.IMAGES, Constants.images);
                        startActivity(intent);
                        break;
                    case 2://我的图片
                        intent = new Intent(MainActivity.this, ImageGridActivity.class);
//                        String tmp[] = {
//                                "http://172.29.115.232:8080/PhotoServer/photo/tmp.jpg",
//                                "http://172.29.115.232:8080/PhotoServer/photo/tmp1.jpg",
//                                "http://172.29.115.232:8080/PhotoServer/photo/tmp2.jpg",
//                                "http://172.29.115.232:8080/PhotoServer/photo/tmp0.png",
//                                "http://172.29.115.232:8080/PhotoServer/photo/tmp2.png"};
//                       // intent.putExtra(Constants.IMAGES, Constants.images);
                        intent.putExtra("serverURL", ConfigURL.myPhotoURL);
                        startActivity(intent);
                        break;
                    case 3://收藏
                        intent = new Intent(MainActivity.this, ImageGridActivity.class);
                        intent.putExtra("serverURL", ConfigURL.myCollectionURL);
                        startActivity(intent);
                        break;
                    case 4://历史
                        intent = new Intent(MainActivity.this, ImageGridActivity.class);
                        intent.putExtra("serverURL", ConfigURL.myHistoryURL);
                        startActivity(intent);
                        break;
                    case 5://修改个人信息
                        AndroidImagePicker.getInstance().clear();
                        intent = new Intent(MainActivity.this,ModifyActivity.class);
                        startActivityForResult(intent,1000);
                        break;
                    case 6:
                        intent = new Intent(MainActivity.this,MapActivity.class);
                        startActivity(intent);
                        break;
                    case 7:
                        break;
                    case 8:
                        intent = new Intent(MainActivity.this,WelcomeActivity.class);
                        startActivity(intent);
                        break;
                }
            }
        });
        mFragments.add(tab01);
        mFragments.add(tab02);
        mFragments.add(tab03);
        mFragments.add(tab04);

    }
    private void setCamera(){
        btn_camera = (ImageButton)findViewById(R.id.btn_camera);
        btn_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AndroidImagePicker.getInstance().clear();
                Intent intent = new Intent(MainActivity.this,CameraActivity.class);
                startActivity(intent);
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        if(requestCode==1000 & resultCode==1001){
            tab04.setTextViewInfo(data.getStringExtra("userInfo"));
            if(data.getBooleanExtra("hasBitmap",false)){
                Bitmap bitmap=data.getParcelableExtra("bitmap");
                Matrix matrix = new Matrix();
                matrix.postScale(2.0f,2.0f); //长和宽放大缩小的比例
                Bitmap resizeBmp = Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);
                Drawable drawable =new BitmapDrawable(resizeBmp);
                UiListView uiListView0  = tab04.getUiListView0();
                uiListView0.clear();
                uiListView0.addBasicItem(new BasicItem(drawable, GetCurrentUser.currentUser.getUserName()));
                uiListView0.commit();
            }
        }
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            if((System.currentTimeMillis()-exitTime) > 2000){
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}